onStart {
  @lever = this
  @lever_base = nil
  # Find lever base
  simulation.bodies.each { |body|
    next if body.group.name != 'lever_base'
    @lever_base = body
    break
  }
  # Store initial lever up direction relative to base.
  up = this.transformation.zaxis.transform(@lever_base.group.transformation.inverse).normalize
  @angle = 0
  # Calculate initial angle
  @init_angle = Math.acos(up.x)
  @init_angle = -@init_angle if up.z < 0
  # Python commando om de seriele bibliotheek te importeren.
  Py.exec("import serial")
  # Python commando om de seriele poort te openen.
  Py.exec("ser = serial.Serial('COM8', 9600)")
}

onUpdate {
  # Get current lever up direction relative to base.
  up = this.transformation.zaxis.transform(@lever_base.group.transformation.inverse).normalize
  # Calculate current angle
  theta = Math.acos(up.x)
  theta = -theta if up.z < 0
  # Get the difference angle
  @angle = theta - @init_angle
  @angle += Math::PI*2 if @angle < -Math::PI
  @angle -= Math::PI*2 if @angle > Math::PI
  # Hoek berekenen
  anglefloat = @angle.radians.round.to_f
  angledata = sprintf "%.2f", (((0.5 / 90) * anglefloat) + 0.5) if anglefloat > 0
  angledata = sprintf "%.2f", (((-0.5 / 90) * anglefloat) - 0.5).abs if anglefloat < 0
  angledata = 0.5 if anglefloat == 0
  # Geef gegevens aan de linkerkant weer.
  logLine("Hendel status: "  + angledata.to_s)
  logLine("Hendel hoek: "  + @angle.radians.round.to_s)
  logLine("")
  logLine("")
  logLine("")
  logLine("")
  logLine("")
  logLine("")
  # Schrijf de data weg naar de seriele poort (incl. newline)
  Py.exec("ser.write(" + angledata.to_s + "\n)")
}

onEnd {
  # Sluit de seriele poort.
  Py.exec("ser.close()")
}